"""
Redis Key管理系统
统一管理所有Redis key的命名规范，确保一致性和可维护性
"""
from typing import Optional
from app.config import get_settings

settings = get_settings()

# 系统前缀
SYSTEM_PREFIX = "kmsg_ui"

class RedisKeys:
    """Redis Key管理类"""
    
    @staticmethod
    def _build_key(*parts: str) -> str:
        """构建Redis key"""
        return f"{SYSTEM_PREFIX}:" + ":".join(str(part) for part in parts if part)
    
    # ==================== Kafka配置相关 ====================
    @staticmethod
    def kafka_config_connection() -> str:
        """Kafka连接配置"""
        return RedisKeys._build_key("kafka", "config", "connection")
    
    # ==================== 监控数据相关 ====================
    @staticmethod
    def monitor_performance_history() -> str:
        """性能监控历史数据"""
        return RedisKeys._build_key("monitor", "performance", "history")
    
    @staticmethod
    def monitor_performance_latest() -> str:
        """最新性能监控数据"""
        return RedisKeys._build_key("monitor", "performance", "latest")
    
    @staticmethod
    def monitor_system_metrics() -> str:
        """系统指标数据"""
        return RedisKeys._build_key("monitor", "system", "metrics")
    
    @staticmethod
    def monitor_topic_offsets(topic_name: str) -> str:
        """Topic偏移量历史数据"""
        return RedisKeys._build_key("monitor", "topic", topic_name, "offsets")
    
    @staticmethod
    def monitor_consumer_group_offsets(group_id: str, topic_name: str) -> str:
        """消费者组偏移量历史数据"""
        return RedisKeys._build_key("monitor", "consumer_group", group_id, "topic", topic_name, "offsets")
    
    @staticmethod
    def monitor_topic_metrics(topic_name: str) -> str:
        """Topic指标数据"""
        return RedisKeys._build_key("monitor", "topic", topic_name, "metrics")
    
    @staticmethod
    def monitor_broker_metrics(broker_id: str) -> str:
        """Broker指标数据"""
        return RedisKeys._build_key("monitor", "broker", broker_id, "metrics")

    @staticmethod
    def monitor_consumer_group_lag(group_id: str, topic_name: str) -> str:
        """消费者组Lag历史数据"""
        return RedisKeys._build_key("monitor", "consumer_group", group_id, "topic", topic_name, "lag")

    @staticmethod
    def monitor_consumer_rate(group_id: str, topic_name: str) -> str:
        """消费者消费速率历史数据"""
        return RedisKeys._build_key("monitor", "consumer_group", group_id, "topic", topic_name, "rate")

    @staticmethod
    def monitor_topic_throughput(topic_name: str) -> str:
        """Topic吞吐量历史数据"""
        return RedisKeys._build_key("monitor", "topic", topic_name, "throughput")

    @staticmethod
    def monitor_partition_metrics(topic_name: str, partition_id: int) -> str:
        """分区级别指标数据"""
        return RedisKeys._build_key("monitor", "partition", topic_name, str(partition_id), "metrics")

    @staticmethod
    def monitor_cluster_health() -> str:
        """集群健康状态历史数据"""
        return RedisKeys._build_key("monitor", "cluster", "health")

    @staticmethod
    def monitor_error_logs() -> str:
        """错误日志监控数据"""
        return RedisKeys._build_key("monitor", "errors", "logs")

    @staticmethod
    def monitor_alerts_history() -> str:
        """告警历史数据"""
        return RedisKeys._build_key("monitor", "alerts", "history")
    
    # ==================== 缓存数据相关 ====================
    @staticmethod
    def cache_topic_metadata(topic_name: str) -> str:
        """Topic元数据缓存"""
        return RedisKeys._build_key("cache", "topic", topic_name, "metadata")
    
    @staticmethod
    def cache_consumer_group_info(group_id: str) -> str:
        """消费者组信息缓存"""
        return RedisKeys._build_key("cache", "consumer_group", group_id, "info")
    
    @staticmethod
    def cache_cluster_info() -> str:
        """集群信息缓存"""
        return RedisKeys._build_key("cache", "cluster", "info")
    
    # ==================== 会话数据相关 ====================
    @staticmethod
    def session_websocket(session_id: str) -> str:
        """WebSocket会话数据"""
        return RedisKeys._build_key("session", "websocket", session_id)
    
    @staticmethod
    def session_consumer(session_id: str, topic_name: str) -> str:
        """消费者会话数据"""
        return RedisKeys._build_key("session", "consumer", session_id, topic_name)
    
    # ==================== 临时数据相关 ====================
    @staticmethod
    def temp_message_batch(batch_id: str) -> str:
        """临时消息批次数据"""
        return RedisKeys._build_key("temp", "message_batch", batch_id)
    
    @staticmethod
    def temp_export_task(task_id: str) -> str:
        """临时导出任务数据"""
        return RedisKeys._build_key("temp", "export_task", task_id)
    
    # ==================== 锁相关 ====================
    @staticmethod
    def lock_topic_operation(topic_name: str, operation: str) -> str:
        """Topic操作锁"""
        return RedisKeys._build_key("lock", "topic", topic_name, operation)
    
    @staticmethod
    def lock_consumer_group_operation(group_id: str, operation: str) -> str:
        """消费者组操作锁"""
        return RedisKeys._build_key("lock", "consumer_group", group_id, operation)
    
    # ==================== 统计数据相关 ====================
    @staticmethod
    def stats_daily_messages(date: str) -> str:
        """每日消息统计"""
        return RedisKeys._build_key("stats", "daily", "messages", date)
    
    @staticmethod
    def stats_hourly_throughput(date: str, hour: str) -> str:
        """每小时吞吐量统计"""
        return RedisKeys._build_key("stats", "hourly", "throughput", date, hour)
    
    # ==================== 配置数据相关 ====================
    @staticmethod
    def config_user_preferences(user_id: str) -> str:
        """用户偏好配置"""
        return RedisKeys._build_key("config", "user", user_id, "preferences")
    
    @staticmethod
    def config_system_settings() -> str:
        """系统设置配置"""
        return RedisKeys._build_key("config", "system", "settings")
    
    # ==================== 工具方法 ====================
    @staticmethod
    def get_pattern(category: str, subcategory: Optional[str] = None) -> str:
        """获取匹配模式"""
        if subcategory:
            return RedisKeys._build_key(category, subcategory, "*")
        return RedisKeys._build_key(category, "*")
    
    @staticmethod
    def get_all_monitor_keys_pattern() -> str:
        """获取所有监控相关key的匹配模式"""
        return RedisKeys._build_key("monitor", "*")
    
    @staticmethod
    def get_all_cache_keys_pattern() -> str:
        """获取所有缓存相关key的匹配模式"""
        return RedisKeys._build_key("cache", "*")
    
    @staticmethod
    def get_all_temp_keys_pattern() -> str:
        """获取所有临时数据key的匹配模式"""
        return RedisKeys._build_key("temp", "*")
    
    @staticmethod
    def parse_key(key: str) -> dict:
        """解析Redis key，返回结构化信息"""
        if not key.startswith(f"{SYSTEM_PREFIX}:"):
            return {"valid": False, "reason": "不是系统key"}
        
        parts = key[len(f"{SYSTEM_PREFIX}:"):].split(":")
        if len(parts) < 2:
            return {"valid": False, "reason": "key格式不正确"}
        
        return {
            "valid": True,
            "system": SYSTEM_PREFIX,
            "category": parts[0],
            "subcategory": parts[1] if len(parts) > 1 else None,
            "parts": parts,
            "full_key": key
        }
    
    @staticmethod
    def is_system_key(key: str) -> bool:
        """检查是否为系统key"""
        return key.startswith(f"{SYSTEM_PREFIX}:")
    
    @staticmethod
    def get_system_prefix() -> str:
        """获取系统前缀"""
        return SYSTEM_PREFIX


# 为了向后兼容，提供一些常用的key常量
REDIS_PERFORMANCE_HISTORY_KEY = RedisKeys.monitor_performance_history()
REDIS_PERFORMANCE_LATEST_KEY = RedisKeys.monitor_performance_latest()
REDIS_SYSTEM_METRICS_KEY = RedisKeys.monitor_system_metrics()

# 导出主要的类和函数
__all__ = [
    'RedisKeys',
    'SYSTEM_PREFIX',
    'REDIS_PERFORMANCE_HISTORY_KEY',
    'REDIS_PERFORMANCE_LATEST_KEY', 
    'REDIS_SYSTEM_METRICS_KEY'
]
